#include <Windows.h>
#include <tchar.h>
#include "resource.h"

int CALLBACK DlgProc(HWND hDlg, UINT nMsg, WPARAM wParam, LPARAM lParam)
{
	switch (nMsg)
	{
		case WM_INITDIALOG:
		{
			SetWindowText(hDlg, _T("Demo0080"));

			UINT nWidth		= GetSystemMetrics(SM_CXSCREEN);
			UINT nHeight	= GetSystemMetrics(SM_CYSCREEN);
			RECT rtClient;
			GetClientRect(hDlg, &rtClient);
			SetWindowPos(hDlg, NULL, (nWidth - (rtClient.right - rtClient.left)) / 2, (nHeight - (rtClient.bottom - rtClient.top)) / 2, 0, 0, SWP_NOSIZE);
			
			break;
		}
		case WM_COMMAND:
		{
			static PROCESS_INFORMATION pi1	= {0};

			switch (LOWORD(wParam))
			{
				case IDC_BTNPROC1:
				{	
					SECURITY_ATTRIBUTES pa, ta;
					pa.nLength				= sizeof(pa);
					pa.bInheritHandle		= TRUE;
					pa.lpSecurityDescriptor	= NULL;

					ta.nLength				= sizeof(pa);
					ta.bInheritHandle		= TRUE;
					ta.lpSecurityDescriptor	= NULL;

					STARTUPINFO si			= {sizeof(STARTUPINFO)};
			
					TCHAR szExePath[256]	= _T("proc1");
					CreateProcess(NULL, szExePath, &pa, &ta, TRUE, 0, NULL, NULL, &si, &pi1);
					
					EnableWindow(GetDlgItem(hDlg, IDC_BTNPROC2), TRUE);

					SetWindowPos(hDlg, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE|SWP_NOMOVE);

					break;
				}
				case IDC_BTNPROC2:
				{
					SECURITY_ATTRIBUTES pa, ta;
					pa.nLength				= sizeof(pa);
					pa.bInheritHandle		= TRUE;
					pa.lpSecurityDescriptor	= NULL;

					ta.nLength				= sizeof(pa);
					ta.bInheritHandle		= TRUE;
					ta.lpSecurityDescriptor	= NULL;

					STARTUPINFO si			= {sizeof(STARTUPINFO)};
					PROCESS_INFORMATION pi2	= {0};
					TCHAR szExePath[256]	= _T("proc2");

					TCHAR szValue[MAX_PATH] = {0};
					_stprintf(szValue, _T("%d"), pi1.hProcess);
					SetEnvironmentVariable(_T("Proc1"), szValue);
					CreateProcess(NULL, szExePath, &pa, &ta, TRUE, 0, NULL, NULL, &si, &pi2);
					
					OutputDebugString(_T("Demo0080: "));
					OutputDebugString(szValue);

					break;
				}
			}
			break;
		}
		case WM_CLOSE:
		{
			PostQuitMessage(0);
			break;
		}
	}

	return 0;
}

BOOL WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hPreInstance, LPTSTR szCmdLine, int nShowCmd)
{
	DialogBox(hInstance, MAKEINTRESOURCE(IDD_DIALOG), NULL, DlgProc);

	return TRUE;
}